/*
 * Copyright (c) 2012 Sean Connelly
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
 * associated documentation files (the 'Software'), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

//
// configuration
//

var config_main = {
		versionPrefix: 'rho:',    // always the same for rho... this indicates where rho starts in a stream
		extendedPrefix: 'rhox:',  // for internal use, in order to identify a Rho-like file with extensions
		versionText: 'v0.0',      // example of the current version at start of rho sources
		maxErrors: 20,            // how many parse errors before we just give up
		maxIdentLength: 50,       // maximum length of an identifier
		maxTypedBitSize: 65536,   // maximum bitsize for `bitX` types, `false` for no limit
		keywords: [               // list of all Rho keywords
				'and',          'as',           'bounce',       'catch',
				'carry',        'case',         'define',       'depart',
				'do',           'elseif',       'else',         'end',
				'eval',         'exit',         'goto',         'if',
				'import',       'is',           'likely',       'metatypein',
				'metatypeof',   'monitorof',    'my',           'next',
				'or',           'override',     'pointerof',    'return',
				'super',        'switch',       'syscall',      'then',
				'throw',        'try',          'typein',       'typeof',
				'unlikely',     'when',         'while'
			],
		rhodents: [ // list of keywords that are 'Rhodents', i.e., represent values/objects
				'my',           'super',        'syscall'
			],
		specials: [ // all special characters that translate directly to tokens
				'~',   '!',   '%',   '^',   '*',   '-',   '+',   '=',   ':',   '<',   ',',   '>',
				'/',   '[',   ']',   '{',   '}',   '@',   '&',   '(',   ')',   '|',   '.',
				'~=',  '!=',  '%=',  '^=',  '*=',  '-=',  '+=',  '==',  '?:',  '<=',  '=>',  '>=',
				'/=',  '#[',  '?[',  '??',  '>>',
				'...', '??='
				// note: if there are ever any 4 character specials, then LexRho needs to be updated
				//       to check for them prior to checking for 3, 2, or 1 character specials inside
				//       the initial state
			],
		macroStart: '#{',
		blockCommentStart: '/*',
		blockCommentEnd: '*/',
		nestCommentStart: '(*',
		nestCommentEnd: '*)',
		rhotextStart: '<<',
		stringInterpStart: '%{', // used for things like this:  text s: "hello, %{name}"
		rhotextInterpStart: '^{', // used for things like this:  say << x^{n} = i
		macroStart: '#{',
		stackingBraces: [ // braces that stack the lexer and require an end brace
				'{', '%{', '^{', '#{'
			],
		binaryPrec: { // binary operator precedence, which also is used to detect if something is a binary operator
				'??':    1,                                 // level 1
				'@':     2,                                 // level 2
				'^':     3,                                 // level 3
				'*':     4, '/':     4, '%': 4,             // level 4
				'+':     5, '-':     5,                     // level 5
				'~':     6,                                 // level 6
				'<':     7, '<=':    7, '>': 7, '>=': 7,    // level 7
				'==':    8, '!=':    8,                     // level 8
				'and':   9,                                 // level 9
				'or':   10,                                 // level 10
				'then': 11, 'else': 11,                     // level 11
				',':    12                                  // level 12
			},
		unaryOps: [ // unary operators
				'-', '+', '@', '!', 'metatypein', 'metatypeof',
				'typein', 'typeof', 'monitorof', 'pointerof'
			],
		ternaryTestOp: 'then',   // ternary operator between the condition/true option
		ternaryElseOp: 'else',   // ternary operator between true/false options
		unaRightToLeft: [        // unary operators that should eval right to left
				'- ^',             // i.e.,   -8 ^ 2      ==>  -(8 ^ 2)
				'+ ^'              // i.e.,   +8 ^ 2      ==>  +(8 ^ 2)
			],
		binRightToLeft: [        // binary operators that should eval right to left
				'^ ^',             // i.e.,   2 ^ 3 ^ 4   ==>  2 ^ (3 ^ 4)
				', ,',             // i.e.,   2, 3, 4     ==>  2, (3, 4)
				'then then',
				'then else',
				'else then'
				// the ternary operator is here because we need to specify how we want to build the
				// tree AS THOUGH they are binary operators... we build the tree in two phases: first,
				// we construct a temporary form (pretending then/else are binary), then we flatten
				// the nodes that are really suppose to be ternary.
				//
				// we do this by enforcing that all then-else statements build in the form of:
				//   input:   a then b else c
				//   middle:  a then (b else c)
				//   tree:
				//              then
				//              /  \
				//             a    else
				//                  /  \
				//                 b    c
				//
				// basically: the right side of the `then` operator MUST ALWAYS be the corresponding
				// `else` operator.
				//
				// given the four possible cases where then-else could be seen ('then then',
				// 'then else', 'else then', and 'else else'), we need to figure out which should be
				// interpretted as right-to-left, or left-to-right, in order to build our target tree
				// above.
				//
				// 'then else' is obvious, since that is our base case above -- it is right-to-left,
				// because the `else` is to the RIGHT of the `then`.
				//
				// 'then then' is found in: a then b then c else d else e
				//                             :1     :2     :3     :4
				// we would want the tree:
				//                           then:1
				//                           /  \
				//                          a    else:4
				//                               /  \
				//                           then:2  e
				//                           /  \
				//                          b    else:3
				//                               /  \
				//                              c    d
				//
				// since then:2 falls to the RIGHT side of then:1, we want 'then then' to be right-to-
				// left.
				//
				// likewise, for 'else else', since else:3 falls to the LEFT side of else:4, 'else else'
				// is left-to-right (and not included on this list).
				//
				// lastly, for 'else then': a then b else c then d else e
				//                             :1     :2     :3     :4
				// we want:
				//                 then:1
				//                 /  \
				//                a    else:2
				//                     /  \
				//                    b    then:3
				//                         /  \
				//                        c    else:4
				//                             /  \
				//                            d    e
				//
				// which means that 'else then' is right-to-left, because then:3 falls to the RIGHT of
				// else:2.
				//
				// in summary:
				//
				//    'then else' => right-to-left
				//    'then then' => right-to-left
				//    'else else' => left-to-right
				//    'else then' => right-to-left
				//
				// therefore, this array should not include 'else else', since it is the only left-to-
				// right operator.
				//
				// having these settings, along with having a separate precedence level for then/else
				// (defined in binaryPrec, at level 11), will guarantee that the tree is built this
				// way.  knowing the tree is built this way, we can flatten then-else structures..
				//
				// from this:
				//              then
				//              /  \
				//             a    else
				//                  /  \
				//                 b    c
				// to this:
				//             ThenElse
				//            /    |   \
				//           a     b    c
				//
				// very easily.
			],
		compareOps: [            // comparison operators, for detecting `a < b < c`
				'<', '>', '<=', '>='
			],
		assignOps: [             // assignment/mutation operators (must be specials)
				'=', '??=', '^=', '*=', '/=', '%=', '+=', '-=', '~='
			]
	};

function config_generateLookup(ar)
{
	var ret = {};
	for (var i = 0; i < ar.length; i++)
		ret[ar[i]] = i;
	return ret;
}

function config_generateLookupFunc(ar)
{
	var lookup = config_generateLookup(ar);
	return function(key) {
			return typeof lookup[key] !== 'undefined';
		};
}

config_main.isKeyword = config_generateLookupFunc(config_main.keywords);
config_main.isRhodent = config_generateLookupFunc(config_main.rhodents);
config_main.isSpecial = config_generateLookupFunc(config_main.specials);
config_main.isUnaryOp = config_generateLookupFunc(config_main.unaryOps);
config_main.isCompareOp = config_generateLookupFunc(config_main.compareOps);
config_main.isAssignOp = config_generateLookupFunc(config_main.assignOps);
config_main.isStackingBrace = config_generateLookupFunc(config_main.stackingBraces);
config_main.isUnaRightToLeft = config_generateLookupFunc(config_main.unaRightToLeft);
config_main.isBinRightToLeft = config_generateLookupFunc(config_main.binRightToLeft);
config_main.isBinaryOp = function(ch) {
		return typeof config_main.binaryPrec[ch] !== 'undefined';
	};

// send config_main to exports
for (var k in config_main)
	exports[k] = config_main[k];
